package com.example.date_save_test;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.example.date_save_test.util.FileUtil;
import com.example.date_save_test.util.ToastUtil;

import java.io.File;

public class FileWriteActivity extends AppCompatActivity implements View.OnClickListener {
    private EditText etFileName;
    private EditText etFileAge;
    private CheckBox ckMarriedFile;
    private String path;
    private TextView tvText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_file_write);

        etFileName = findViewById(R.id.et_fileName);
        etFileAge = findViewById(R.id.et_fileAge);
        ckMarriedFile = findViewById(R.id.cK_marryFile);

        findViewById(R.id.btn_saveDataFile).setOnClickListener(this);
        findViewById(R.id.btn_readDataFile).setOnClickListener(this);
        tvText = findViewById(R.id.tv_txt);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_saveDataFile:
                StringBuilder sbi = new StringBuilder();
                sbi.append("姓名:").append(etFileName.getText().toString());
                sbi.append("\n年纪:").append(etFileAge.getText().toString());
                sbi.append("\n婚否:").append(ckMarriedFile.isChecked() ? "是" : "否");

                String fileName = System.currentTimeMillis() + ".txt";
                String directory = null;
                //外部存储打私有空间,应用卸载数据消失
//                directory = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).toString();
//                外部存储公共空间,应用卸载数据还在
//                directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString();
//                内部存储私有空间,应用卸载数据消失
                directory = getFilesDir().toString();
                path = directory + File.separatorChar + fileName;
                Log.d("NING",path);
                FileUtil.saveText(path, sbi.toString());
                ToastUtil.successShow(this, "保存成功");
                break;
            case R.id.btn_readDataFile:
                tvText.setText(FileUtil.readText(path));
                break;
        }
    }
}